package logger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.DirectoryIteratorException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Logger {

	public static final Logger INSTANCE = new Logger();
	
	private BufferedWriter buffer;
	private DateFormat hourFormat = new SimpleDateFormat("hh:mm:ss");
	
	private Logger()
	{
		FileOutputStream flux = null;
		try {
			DateFormat format = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss");
			File f1 = new File("log");
			if(!f1.exists())
				f1.mkdir();
			
			File f = new File("log/log_"+format.format(Calendar.getInstance().getTime())+".txt");
			if(!f.exists())
				f.createNewFile();
			flux = new FileOutputStream("log/log_"+format.format(Calendar.getInstance().getTime())+".txt");
		} catch (Exception e) {
			e.printStackTrace();
		} 

		OutputStreamWriter fluxOut = new OutputStreamWriter(flux);
		buffer=new BufferedWriter(fluxOut); 	
	}
	
	private void writeInLog(String line)
	{
		try {
			buffer.write("["+hourFormat.format(Calendar.getInstance().getTime())+"] : "+line+"\n");
			buffer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void logMessage(String message)
	{
		System.out.println("["+hourFormat.format(Calendar.getInstance().getTime())+"] INFO : "+message);
		writeInLog("INFO : "+message);
	}
	
	public void logWarning(String message)
	{
		System.out.println("["+hourFormat.format(Calendar.getInstance().getTime())+"] WARN : "+message);
		writeInLog("WARN : "+message);
	}
	
	public void logWarning(Exception ex)
	{
		System.err.println("["+hourFormat.format(Calendar.getInstance().getTime())+"] WARN : ");
		ex.printStackTrace();
		writeInLog(ex.getMessage());
	}
	
	public void logError(String message)
	{
		System.err.println("["+hourFormat.format(Calendar.getInstance().getTime())+"] ERROR : "+message);
		writeInLog("ERROR : "+message);
	}
	
	public void logError(Exception ex)
	{
		System.err.println("["+hourFormat.format(Calendar.getInstance().getTime())+"] ERROR : ");
		ex.printStackTrace();
		writeInLog(ex.getMessage());
	}
}
